<template >
  <div class="flow-form" :style="{margin: '0 auto',width:formConf.fullScreenWidth}">
     <parser :form-conf="formConf" @submit="submitForm" :key="key" :relationInfo="relationInfo" ref="dynamicForm"
      v-if="!loading" />
    <candidate-form :visible.sync="candidateVisible" :candidateList="this.candidateList"
      @submitCandidate="selfHandleRequest" :formData="dataForm" />

      <DiagnosisBox v-if="diagnosisBoxVisible" ref="DiagnosisBox"  @refreshDataList="refresh"/>
   
      
  </div>
</template>
<script>
import { DynamicInfo } from '@/api/workFlow/workFlowForm'
import { createModel, updateModel, getModelInfo } from '@/api/onlineDev/visualDev'
import { Candidates } from '@/api/workFlow/FlowBefore'
import Parser from '@/components/Generator/parser/Parser'
import CandidateForm from '@/views/workFlow/components/CandidateForm'
import DiagnosisBox from './DiagnosisBox'
import { deepClone } from '@/utils'
export default {
  components: { Parser, CandidateForm,DiagnosisBox },
  props: {
    relationInfo: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      formData: {},
      loading: true,
      eventType: '',
      key: +new Date(),
      formConf: {},
      candidateVisible: false,
      diagnosisBoxVisible:false,
      candidateList: [],
      dataForm: {
        id: '',
        data: '',
        flowId: ''
      },
      existSubTableList:false,
      listTables:[],
      clientUUID:'', // by jdeng 用于在client生成id，主要场景是为子表在创建状态也能操作
      subFieldMap:{},// by jdeng 子表与主表的字段映射扁平化
    }
  },
  beforeDestroy() {
    if(!this.relationInfo){ // by jdeng 将主表数据缓存在全局变量中，用于子表对应字段做自动填充
      this.$store.commit('generator/SET_MAINTABLE_DYNAMIC_MODEL_EXTRA', {})
      this.$store.commit('generator/SET_MAINTABLE_OBJ', {})
    }
  },
  methods: {
    init(data) {
      debugger
      
      this.$store.commit('generator/SET_VIEW_STATUS', 'edit')

      this.setting = data
      this.formConf = data.formConf ? JSON.parse(data.formConf) : {}
      this.dataForm.id = data.id || ''
      this.loading = true
       /**
       * by jdeng
       */
       this.formatSubFieldMap()
      // end
      this.$nextTick(() => {
        if (this.dataForm.id) {
          this.clientUUID = ''
          let extra = {
            modelId: data.flowId,
            id: this.dataForm.id,
            type: data.type,
            processId: data.id,
            taskId: data.taskId,
            opType: data.opType,
            flowId: data.flowId,
            thisStep: data.thisStep,
            isNew:false
          }
          this.$store.commit('generator/SET_DYNAMIC_MODEL_EXTRA', extra)
          if (data.draftData) {
            this.formData = data.draftData
            this.fillFormData(this.formConf, this.formData)
            this.$nextTick(() => {
              this.loading = false
              this.$emit('setPageLoad')
            })
            return
          }
          if (data.type == 1) {
            getModelInfo(data.flowId, this.dataForm.id).then(res => {
              this.dataForm = res.data
              if (!this.dataForm.data) return
              this.formData = JSON.parse(this.dataForm.data)
               /**
             * by jdeng
             */
              if(!this.relationInfo){ // 将主表数据缓存在全局变量中，用于子表对应字段做自动填充
                // this.$store.commit('generator/SET_MAINTABLE_DYNAMIC_MODEL_EXTRA', this.formatMainFormData(this.formConf,this.formData))
                this.$store.commit('generator/SET_MAINTABLE_OBJ', this)
              }

              this.fillFormData(this.formConf, this.formData)
              this.$nextTick(() => {
                this.loading = false
                this.$emit('setPageLoad')
              })
            })
          } else {
            DynamicInfo(this.dataForm.id).then(res => {
              this.dataForm = res.data
              if (!this.dataForm.data) return
              this.formData = JSON.parse(this.dataForm.data)
              this.fillFormData(this.formConf, this.formData)
              this.$nextTick(() => {
                this.loading = false
                this.$emit('setPageLoad')
              })
            })
          }
          
        } else {
          this.clientUUID = this.hlsz.guid()
          // this.$store.commit('generator/SET_DYNAMIC_MODEL_EXTRA', {})
          this.formData = {}
          /**
           * by jdeng
           */
          let extra = {
            modelId: data.flowId,
            id: this.clientUUID,
            type: data.type,
            flowId: data.flowId,
            processId: data.id,
            taskId: data.taskId,
            opType: data.opType,
            taskId: data.taskId,
            thisStep: data.thisStep,
            isNew:true
          }
          this.$store.commit('generator/SET_DYNAMIC_MODEL_EXTRA', extra)
          
          if(!this.relationInfo){ // 将主表数据缓存在全局变量中，用于子表对应字段做自动填充
            this.$store.commit('generator/SET_MAINTABLE_DYNAMIC_MODEL_EXTRA', {})
            this.$store.commit('generator/SET_MAINTABLE_OBJ', this)
          }

          this.fillFormData(this.formConf, this.formData)
          this.$nextTick(() => {
            this.loading = false
            this.$emit('setPageLoad')
          })
          this.dataForm.flowId = data.flowId
          
        }
        this.key = +new Date()
      })
    },

    /**
     * by jdeng 子表与主表的字段映射扁平化
     */
     formatSubFieldMap(){
      debugger
      if(this.relationInfo&&this.relationInfo.fieldMap){
        let map = {}
        this.relationInfo.fieldMap.forEach((o)=>{
          if(o.tableField&&o.relationField){
            map[o.tableField] = o.relationField
          }
        })
        this.subFieldMap = map
      }
    },
    /**
     * by jdeng
     * 扁平化主表的字段和值的对应关系
     * 用于子表对应字段做自动填充
     * @param {*} data 
     */
    formatMainFormData(form,data){
      let mainData = {}
      const loop = list => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            const val = data[item.__vModel__]
            if (val !== undefined) {
              mainData[item.__vModel__] = val
            }
          }
          // end by jdeng
          if (item.__config__ && item.__config__.jnpfKey !== 'table' && item.__config__.jnpfKey !== 'listTable' && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children)
          }
        }
      }
      loop(form.fields)
      debugger
      return mainData
    },
    resetMainTableAllFieldValue(){
      this.$refs.dynamicForm && this.$refs.dynamicForm.resetMainTableAllFieldValue && this.$refs.dynamicForm.resetMainTableAllFieldValue()
    },

    fillFormData(form, data) {
      form.disabled = this.setting.readonly
      // by jdeng
      this.initDynamicConfig(form.fields,data)
      // end by jdeng
      const loop = (list, parent) => {
        for (let i = 0; i < list.length; i++) {
          let item = list[i]
          if (item.__vModel__) {
            let val = data[item.__vModel__]
             /**
               * by jdeng
               */
               if(this.relationInfo&&this.subFieldMap){
                 debugger
                 let mainField = this.subFieldMap[item.__vModel__]
                 if(mainField){
                  let mainTableDynamicModelExtra = this.$store.state.generator.mainTableDynamicModelExtra
                  if(mainTableDynamicModelExtra){
                    let mainValue = mainTableDynamicModelExtra[mainField]
                    if(mainValue !== undefined){
                      val = mainValue
                    }
                  }
                 }
               }
            if (val !== undefined && val != null && !item.__config__.isSubTable) {
              item.__config__.defaultValue = val
            }
            let noShow = false, isDisabled = false, required = false
            if (this.setting.formOperates && this.setting.formOperates.length) {
              let id = item.__config__.isSubTable ? parent.__vModel__ + '-' + item.__vModel__ : item.__vModel__
              // debugger
              let arr = this.setting.formOperates.filter(o => o.id === id) || []
              if (arr.length) {
                let obj = arr[0]
                noShow = !obj.read
                isDisabled = !obj.write
                required = obj.required ? obj.required : item.__config__.required
              }
            }
            isDisabled = item.disabled ? item.disabled : isDisabled
            noShow = item.__config__.noShow ? item.__config__.noShow : noShow
            if (this.setting.readonly) isDisabled = true
              this.$set(item, 'disabled', isDisabled)
              this.$set(item.__config__, 'noShow', noShow)
              this.$set(item.__config__, 'required', required || false)
            }
            /**
           * by jdeng 设置defaultValue
           */
          if (item.__config__ && item.__config__.jnpfKey === 'listTable'){
            this.existSubTableList = true
            // 在src/components/Generator/parser/Parser.vue中会将__config__.defaultValue赋值给foreignId属性
            item.__config__.defaultValue = this.dataForm.id?this.dataForm.id:this.clientUUID
            this.$set(item.__config__, 'viewStatus', 'edit')
            debugger
            let __subTableDatas__ = data['__subTableDatas__']
            if(__subTableDatas__){
              let subData = __subTableDatas__[item.__config__.tableName]
              this.$set(item.__config__, 'initData', subData)
            }
            this.listTables.push(deepClone(item))

          }
          if (item.__config__ && item.__config__.children && Array.isArray(item.__config__.children)) {
            loop(item.__config__.children, item)
          }
        }
      }
      loop(form.fields)
      this.fillForeignId(form.fields,data)
    },
    fillForeignId(componentList,formData){
      debugger
      if(!this.relationInfo){
        return
      }
      let {foreignField,foreignId} = this.relationInfo
      if(foreignField&&foreignId){
        componentList.forEach(cur => {
          if (cur.__vModel__ === foreignField) {
            cur.__config__.defaultValue = foreignId
            return;
          }
        })
      }
    },
    /**
     * by jdeng 解析动态配置
     * @param {*} componentList 
     */
     initDynamicConfig(componentList,formData){
      debugger
      let dynamicItem
      componentList.forEach(cur => {
        if (cur.__vModel__ === 'F_FormDynamicConf') {
          dynamicItem = cur
          return;
        }
      })
      if(!dynamicItem){
        return;
      }
      const config = dynamicItem.__config__
      const vModel = dynamicItem.__vModel__
      const initConfigCall = (list,key,prop,value)=>{
        list.forEach(cur => {
          const config = cur.__config__
          if (cur.__vModel__ === key) {
            config[prop]=value
            return
          }
          if (cur.__config__.jnpfKey == 'table') return
          if (config.children) initConfigCall(config.children, key,prop,value)
        })
      }
      try{
          let dynamicJsonStr = formData[vModel]
          if(dynamicJsonStr){
            config.defaultValue = dynamicJsonStr
            let dynamicJson = JSON.parse(dynamicJsonStr)
            if(dynamicJson){
              if(dynamicJson.showOrHide){ // 动态设置显示隐藏属性
                let showOrHide = dynamicJson.showOrHide
                for (let key in showOrHide) {
                  const newVal = !!showOrHide[key]
                  initConfigCall(componentList,key,'noShow',!newVal)
                }
              }
              if(dynamicJson.currency){ // 动态设置显示隐藏属性
                let currency = dynamicJson.currency
                for (let key in currency) {
                  const newVal = currency[key]
                  initConfigCall(componentList,key,'currency',newVal)
                }
              }
              if(dynamicJson.flowStag){ // 动态设置流程步骤属性
                
              }
            }
           
          }
      }catch(e){
        console.error(e)
      }
    },


    submitForm(data, callback) {
      if (!data) return

       /**
       * by jdeng
       */
       this.dataForm.clientUUID = !this.existSubTableList||this.dataForm.id ?'':this.clientUUID
      // end by jdeng

      this.doAllTableSubmit((subDataForms,callbacks)=>{
        debugger
        this.dataForm.data = JSON.stringify(data)
        if(subDataForms){
          this.dataForm.subDataForms = JSON.stringify(subDataForms)
        }
        if (callback && typeof callback === "function") callback()
        if (this.setting.type == 1) {
          if (this.eventType === 'save' || this.eventType === 'submit') {
            this.selfSubmit()
            return
          }
          this.$emit('eventReceiver', this.dataForm, this.eventType)
        } else {
          this.$emit('eventReceiver', this.dataForm, this.eventType)
        }
      })

      
    },
    selfSubmit() {
      this.dataForm.status = this.eventType === 'submit' ? 0 : 1
      this.dataForm.flowId = this.setting.flowId
      if (this.eventType === 'save') return this.selfHandleRequest()
      this.$emit('setCandidateLoad', true)
      Candidates(0, { formData: this.dataForm }).then(res => {
        let data = res.data
        this.$emit('setCandidateLoad', false)
        if (Array.isArray(data) && data.length) {
          this.candidateList = res.data
          this.candidateVisible = true
        } else {
          this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
            type: 'warning'
          }).then(() => {
            this.selfHandleRequest()
          }).catch(() => { });
        }
      }).catch(() => {
        this.$emit('setCandidateLoad', false)
      })
    },
    selfHandleRequest(candidateList) {
      if (candidateList) this.dataForm.candidateList = candidateList
      if (!this.dataForm.id) delete (this.dataForm.id)
      if (this.eventType === 'save') this.$emit('setLoad', true)
      const formMethod = this.dataForm.id ? updateModel : createModel
      formMethod(this.setting.flowId, this.dataForm).then(res => {
        this.$message({
          message: res.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
            if (this.eventType === 'save') this.$emit('setLoad', false)
            this.candidateVisible = false
            this.$emit('close', true)
          }
        })
      }).catch(() => {
        if (this.eventType === 'save') this.$emit('setLoad', false)
      })
    },
    dataFormSubmit(eventType) {
      if (this.setting.isPreview) return this.$message({ message: '功能预览不支持数据保存', type: 'warning' })
      this.eventType = eventType
      this.$refs.dynamicForm && this.$refs.dynamicForm.submitForm()
    },
    /**
     * 
     * by jdeng
     */
     doAllTableSubmit(mainCallback){
      debugger
      if(this.$refs.dynamicForm&&this.listTables&&this.listTables.length>0){
        let count = this.listTables.length
        let index = 0
        let callbacks = []
        let subDataForms = {}
        let nextFun = (item,subData,callback)=>{
          debugger
          index++
          let obj = {}
          if(subData){
            subDataForms[item.__config__.tableName] = subData
          }
          if(callback){
            callbacks.push(callback)
          }
          
          if(index===count){
            mainCallback(subDataForms,callbacks)
          }
        }
        this.listTables.forEach((item,index)=>{
          let ref = 'listTable_'+item.__config__.tableName
          let listTableComp = this.$refs.dynamicForm.$refs[ref]
          if(listTableComp
            &&listTableComp.$refs.listTable){
              let subDynamicForm = listTableComp.$refs.listTable.$refs.dynamicForm
              if(subDynamicForm){
                debugger
                subDynamicForm.doSubFormSubmit((subData,callback)=>{
                  nextFun(item,subData,callback)
                })
              }
          }
        })
      }else{
        mainCallback()
      }
     
    },
    refresh(isRefresh) {
      this.diagnosisBoxVisible = false
      if (isRefresh) 
        this.init(this.setting)
    }
  }
}
</script>